package com.example.lt.controller.admin;

import com.example.lt.constant.MessageConstants;
import com.example.lt.context.LocalCache;
import com.example.lt.entity.Setting;
import com.example.lt.entity.json.SettingScoreJson;
import com.example.lt.service.SettingService;
import com.example.lt.util.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author 小涛Tao
 * @Date: 2024/08/18/19:56
 * version 1.0 注释：
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/setting")
public class AdminSettingController {

    private final SettingService settingService;

    private ObjectMapper objectMapper = new ObjectMapper();


    /**
     * 获取系统配置的审核力度参数
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping
    public Result get() throws JsonProcessingException {
        log.info("获取系统配置的审核力度参数");
        final Setting setting = settingService.list(null).get(0);
        // 将审核力度字符串转换成 SettingScoreJson 对象
        final SettingScoreJson settingScoreJson = objectMapper.readValue(setting.getAuditPolicy(), SettingScoreJson.class);
        setting.setSettingScoreJson(settingScoreJson);
        return Result.ok().data(setting);
    }

    /**
     * 修改系统配置的审核力度参数
     * @param setting 系统参数
     * @return
     */
    @PutMapping
    public Result update(@RequestBody @Validated Setting setting) {
        log.info("修改系统配置的审核力度参数");
        settingService.updateById(setting);
        for (String s : setting.getAllowIp().split(",")) {
            LocalCache.put(s, true);
        }
        return Result.ok().message(MessageConstants.UPDATE_SUCCESS);
    }

}
